<?php
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
require('include.php');
use Admin\Controller\Tencentyun\Conf;
use Admin\Controller\Tencentyun\ImageV2;
use Admin\Controller\Tencentyun\Auth;
use Admin\Controller\Tencentyun\ImageProcess;
use Common\Model\LiveCameraAngleModel;
use Common\Model\LiveManagerModel;
use Common\Model\NewsVideoModel;
use Common\Model\LiveVideoModel;
use Common\Model\LivePanelManageModel;
use Think\Cache\Driver\Redis;
use Common\Model\NewsRewardModel;

class LiveController extends AdminbaseController{
	private $live;
	private $live_channel;
	private $live_channel_operator;
	private $live_competitor;
	private $live_news_relation;
	private $live_camera_angle;
	private $live_video;
	private $live_resource_video;
	private $news;
	private $admin_user_rcloud_token;
	private $live_panel_manage;
	
	function _initialize() {
		parent::_initialize();
		$this->live = D("Common/Live");
		$this->live_channel = D("Common/LiveChannel");
		$this->live_channel_operator = D("Common/LiveChannelOperator");
		$this->live_competitor = D("Common/LiveCompetitor");
		$this->live_news_relation = D("Common/LiveNewsRelation");
		$this->live_camera_angle = D("Common/LiveCameraAngle");
		$this->live_video = D("Common/LiveVideo");
		$this->live_resource_video = D("Common/LiveResourceVideo");
		$this->news = D("Common/News");
		$this->admin_user_rcloud_token = D("Common/AdminUserRcloudToken");
		$this->live_panel_manage = D("Common/LivePanelManage");
                $this->user_admin_model = D("Common/AdminUser");
                $admin_id = $_SESSION["ADMIN_ID"];
                $this->company_id = $this->user_admin_model->where(array('admin_id' => $admin_id))->getField('company_id');
	}
	
	function index(){
		$admin_id = $_SESSION['ADMIN_ID'];
		$status = I("post.status", -1);
		$category = I("post.category", -1);
		$name = I("post.name", "");
		$count = $this->live->queryLiveCount($status, $name, $category);
		$page = $this->page($count, 20);
		
		$result = $this->live->queryLiveList($status, $name, $category, $page->firstRow , $page->listRows); //获取直播列表
		if($result && !empty($result)){
			foreach($result as $key=>&$value){
				$start_time = strtotime($value['start_time']);
	    		$status1 = $value['status'];
	    		if($start_time > time()){  //开始时间大于当前时间：未开始
	    			$value['status'] = 3;
	    		}else if(2 == $status1 || 5 == $status1){ //已结束
	    			$value['status'] = $status1;
	    			if($value['red_score'] && !empty($value['red_score'])){  //结果已公布，返回红方蓝方的信息
	    				$red_competitor_id = $value["red_competitor_id"];
	    				$blue_competitor_id = $value["blue_competitor_id"];
	    				$red = $this->live_competitor->find($red_competitor_id);
	    				$blue = $this->live_competitor->find($blue_competitor_id);
	    				$value['red_competitor'] = $red['real_name'];
	    				$value['blue_competitor'] = $blue['real_name'];
	    			}
	    		}else{ //直播中
	    			$value['status'] = 4;
				}

				//获取打赏汇闻币
				$news_reward = new NewsRewardModel();
				$news_reward_list = $news_reward->where("live_id = ".$value['live_id'])->field("hw_money")->select();
				$result[$key]['hw_money_total'] = '0';
				foreach($news_reward_list as $reward_key=>$reward_value){
					$result[$key]['hw_money_total'] +=$reward_value['hw_money'];//number_format($reward_value['hw_money'],'2');
				}
				
			}
		}
		
		//当前用户是否支持查看真是浏览量
		$user_can_show_count = '0';
		if($_SESSION['ADMIN_ID'] !='1'){
			$show_count_menu_id = M('vradmin1.sys_menu')->where(array('name'=>'查看真实浏览数'))->getField('menu_id');
			$show_count_sys_menu_id = M('vradmin1.sys_menu_admin')->where(array('admin_id'=>$_SESSION['ADMIN_ID'],'menu_id'=>$show_count_menu_id))->getField('id');
			if($show_count_sys_menu_id){
				$user_can_show_count = '1';
			}
		}else{
			$user_can_show_count = '1';
		}

		$this->assign("user_can_show_count",$user_can_show_count);
		$this->assign("data", $result);
		$this->assign("formParam", array('status'=>$status,'name'=>$name,'category'=>$category));
		$this->assign("page", $page->show('Admin'));
		$this->assign("admin_id", $admin_id);
		$this->display();
	}
	
	function add(){
		$admin_ids = I("admin_ids");
		$usernames = I("usernames");

		if(empty($usernames)){
			$arr_usernames = '';
		}else{
			$arr_usernames = explode(',',$usernames);
		}
		if(empty($admin_ids)){
			$arr_admin_ids = '';
		}else{
			$arr_admin_ids = explode(',',$admin_ids);
		}


		//全部 管理员
		$admins = M("vradmin1.admin_user",null);
		$admin_infos = $admins
			->where("type = 2 and status = 1")
			->select();

		$this->assign("arr_admin_ids",$arr_admin_ids);
		$this->assign("arr_usernames",$arr_usernames);
		$this->assign("admin_infos",$admin_infos);
		$this->assign("admin_ids",$admin_ids);
		$this->assign("usernames",$usernames);


		$add_from = I("add_from",0);//来源于 1 新闻添加直播
		$column_id = I("column_id") ? I("column_id") : '';
		$area_id   = I("area_id") ? I("area_id") : '';
		$news_id   = I("news_id") ? I("news_id") : '';

		if($column_id){
			$id_type = "column_id";
			$id_val  = $column_id;
		}else{
			$id_type = "area_id";
			$id_val  = $area_id;
		}
		
		//直播类型 Tah 20161208，新增字段
		//alter table live add live_type tinyint(4) default '0' COMMENT '直播类型：0：表示未设置直播类型,请选择；1视频直播；2VR直播;3图文直播'
 		$liveType = array("0"=>"请选择","1"=>"视频直播","2"=>"VR直播","3"=>"图文直播","4"=>"视频加图文直播","5"=>"VR加图文直播");		
 		
 		//定义直播未开始、进行中、以已结束状态下的浏览数随机增加的范围
 		$view_range_list = array("0"=>"5-10","1"=>"1-20","2"=>"1-5");

		//查询频道
		$channelList = $this->live_channel->getLiveChannelList();
		//查询选手
		$competitorList = $this->live_competitor->getLiveCompetitorList();
		$admin_id = $_SESSION['ADMIN_ID'];
		
		$this->assign("add_from",$add_from);
		$this->assign("id_type",$id_type);
		$this->assign("id_val",$id_val);
		$this->assign("news_id",$news_id);
		
		$this->assign("liveType", $liveType);
		$this->assign("channelList", $channelList);
		$this->assign("competitorList", $competitorList);
		$this->assign("view_range_list", $view_range_list);
		$this->assign("admin_id", $admin_id);
		$this->display();
	}
	
	
	function live_reward_list(){
		$live_id = I("live_id") ? I("live_id") : '';
		$this->assign('live_id',$live_id);
		$this->display('live_reward_lists');
	}
	

	//直播 新闻管理 页面
	public function manage(){
		$add_from = I("add_from",0);//来源于 1 新闻添加直播
		$column_id = I("column_id") ? I("column_id") : '';
		$area_id   = I("area_id") ? I("area_id") : '';
		$news_id   = I("news_id") ? I("news_id") : '';

		if($column_id){
			$id_type = "column_id";
			$id_val  = $column_id;
		}else{
			$id_type = "area_id";
			$id_val  = $area_id;
		}

		//查看直播详情
		$live = M("vrlive.live")->where("news_id = ".$news_id)->find();

		$start_time = strtotime($live['start_time']);
		$status1 = $live['status'];
		if($start_time > time()){  //开始时间大于当前时间：未开始
			$live['status'] = 3;
		}else if(2 == $status1 || 5 == $status1){ //已结束
			$live['status'] = $status1;
		}else{ //直播中
			$live['status'] = 4;
		}

		$this->assign("live",$live);
		$this->assign("add_from",$add_from);
		$this->assign("id_type",$id_type);
		$this->assign("id_val",$id_val);
		$this->assign("news_id",$news_id);
		$this->display();
	}
	
	function add_post(){
		if(IS_POST){
			//接受手填视频信息
			$file_id1 =  I("file_id1");  //未开始视频file_id
			$qcloud_file_name1 =  I("qcloud_file_name1");  //未开始视频文件名
			$file_id2 =  I("file_id2");  //回放视频
			$qcloud_file_name2 =  I("qcloud_file_name2");
			$add_from  = isset($_GET['add_from']) ? $_GET['add_from'] : 0; //来源 1新闻
			$column_id = isset($_GET["column_id"]) ? $_GET["column_id"] : '';
			$area_id   = isset($_GET["area_id"]) ? $_GET["area_id"] : '';
//			$screen    = I("screen") ? I("screen") : 0; //画面方向 默认0横屏


			if($column_id){
				$id_type = "column_id";
				$id_val  = $column_id;
			}else{
				$id_type = "area_id";
				$id_val  = $area_id;
			}
			
			$liveType = I("post.liveType", '');
			if(empty($liveType)){
				return $this->error("请选择直播类型！");
			}
						
			$quiz_status = I("post.quiz_status");
			$prop_status = I("post.prop_status");
			$name = I("post.name", '');
			if(empty($name)){
				return $this->error("直播名称不能为空！");
			}
			
			$live_man_cate = I("post.live_man_cate", '');
			$live_man_alias = I("post.live_man_alias", '');
			
			if(in_array($liveType, array(3,4,5))){
				if(empty($live_man_cate)){
					return $this->error("请填写直播员类别！");
				}
				if(empty($live_man_alias)){
					return $this->error("请填写直播员别名！");
				}
				if(!isset($_FILES['avatar_file'])){
					return $this->error("请上传直播员头像！");
				}
//				if(I("live_admin_ids") == ','){
//					return $this->error("请选择直播业务员");
//				}
			}

			$is_fast = 0;
			if(I('fast_live_status') == 'on'){
				$is_fast = 1;
			}
//			if(in_array($liveType,array(1,4)) && $is_fast == 1) {
//				if (!I("live_channel_res")) {
//					return $this->error("请选择 直播推流业务员");
//				}
//			}
			
			$weight = I("post.weight", 70);
				
			if (!preg_match('/^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/', $weight)) {
				return $this->error("权重必须为0到255的数字！");
			}
			
			$start_time = I("post.start_time", '');
			if(empty($start_time)){
				return $this->error("开始时间不能为空！");
			}
			
			$weight = I("post.weight", 70);
		    //if(empty($_FILES) || !isset($_FILES['imageFile'])){
			if(!isset($_FILES['imageFile'])){
				return $this->error("请上传封面图片！");
			}
			
				
			$type = I("post.type", 1);  //赛事信息
			$red_competitor_id = I("post.red_competitor_id", 0);
			$red_news_url = I("post.red_news_url", '');
			if('' == $red_news_url){
				$red_news_id = 0;  //红方专题id
			}else{
				$red_news_id = $this->get_news_id($red_news_url)['id'];
			}
			$blue_competitor_id = I("post.blue_competitor_id", 0);
			$blue_news_url = I("post.blue_news_url", '');
			if('' == $blue_news_url){
				$blue_news_id = 0;
			}else{
				$blue_news_id = $this->get_news_id($blue_news_url)['id'];
			}
			$news_status = I("post.news_status", 0);  //相关新闻
			
			$introduction_status = I("post.introduction_status", 0); //直播介绍
			
			$title = I("post.title", '');
			$introduction = I("post.introduction", '');
			
			//获取未直播、直播中、直播结束三状态下访问直播时的设置的随机增加访问量数的值
			$no_start_view_ranage_from = I("post.no_start_view_ranage_from", '5');
			$no_start_view_ranage_to = I("post.no_start_view_ranage_to", '10');
			$loading_view_ranage_from = I("post.loading_view_ranage_from", '20');
			$loading_view_ranage_to = I("post.loading_view_ranage_to", '100');
			$end_view_ranage_from = I("post.end_view_ranage_from", '1');
			$end_view_ranage_to = I("post.end_view_ranage_to", '5');
			$view_ranage = $no_start_view_ranage_from.'-'.$no_start_view_ranage_to.'|'.$loading_view_ranage_from.'-'.$loading_view_ranage_to.'|'.$end_view_ranage_from.'-'.$end_view_ranage_to;
				
			
			$remark = I("post.remark", '');
			
			$upload = new \Think\Upload();// 实例化上传类
			$upload->maxSize   =     59614161 ;// 设置附件上传大小
			$upload->exts      =     array('jpeg', 'jpg', 'bmp', 'png');// 设置附件上传类型
			$upload->rootPath  =     C('UPLOADPATH'); // 设置附件上传根目录
			$upload->savePath  =     ''; // 设置附件上传（子）目录
			
			// 上传文件
			$info = $upload->upload();
			if(!$info) {// 上传错误提示错误信息
				$this->error($upload->getError());
			}else{
				$cname = C('UPLOADPATH').$info['imageFile']['savepath'].$info['imageFile']['savename'];
				$fileName = 'lv'.time().$info['imageFile']['savename'];  // 自定义文件名
				$uploadRet = ImageV2::upload($cname, Conf::BUCKET, $fileName);
				\Think\Log::record('上传封面万象优图返回：'.json_encode($uploadRet), 'INFO');
				if(($uploadRet['httpcode'] == 200)){
					$image_url = $uploadRet['data']['downloadUrl'];
					//删除本地文件
					unlink($cname);
				}else{
					return $this->error('图片上传腾讯云失败，请联系系统管理员！');
				}
				if(in_array($liveType, array(3,4,5))){
					$cname2 = C('UPLOADPATH').$info['avatar_file']['savepath'].$info['avatar_file']['savename'];
					$fileName2 = 'lv'.time().$info['avatar_file']['savename'];  // 自定义文件名
					$uploadRet2 = ImageV2::upload($cname2, Conf::BUCKET, $fileName2);
					\Think\Log::record('上传封面万象优图返回：'.json_encode($uploadRet2), 'INFO');
					if(($uploadRet['httpcode'] == 200) && ($uploadRet2['httpcode'] == 200)){
						$live_man_avatar_url = $uploadRet2['data']['downloadUrl'];//直播员头像//Tah 20161209
						//删除本地文件
						unlink($cname2);
					}else{
						return $this->error('图片上传腾讯云失败，请联系系统管理员！');
					}
				}else{
					$live_man_avatar_url = 'http://vrlive-10047449.image.myqcloud.com/lv1481274674584a7532dc9b1.png';
				}
				
				$live_id = $this->create_live_id();
				
				if (in_array($liveType,array(3,4,5))){
					//创建图文直播聊天室
					$code = $this->create_rcloud_chroom_pic_txt($live_id);
					if ($code==200){
// 						//创建一个额外的聊天室		
// 						$this->create_rcloud_chroom_pic_txt($live_id);
					}else{
						return $this->error('创建融云图文直播聊天室失败，请联系系统管理员！');
					}
				}
				
				//创建融云聊天室
				$code = $this->create_rcloud_chroom($live_id);
				if($code == 200){
					$is_vr1 = I("post.is_vr1", '1');
					$is_vr2 = I("post.is_vr2", '1');
					$create_time = date('Y-m-d H:i:s');
					$param = array(
							'category'=>$liveType,
							'live_man_cate'=>$live_man_cate,
							'live_man_alias'=>$live_man_alias,
							'live_id' => $live_id,
							'name'	  => $name,
							'weight'  => $weight,
							'start_time' => $start_time,
							'image_url' => $image_url,
							'live_man_avatar_url'	=>	$live_man_avatar_url,
							'introduction_status' => $introduction_status,
							'title'   => $title,
							'introduction' => $introduction,
							'remark'    => $remark,
							'type'    => $type,
							'befor_video_category' =>$is_vr1,
							'rever_video_category' =>$is_vr2,
							'create_time' => $create_time,
							'update_time' => $create_time,
							'refresh_time' => $create_time,
							'creator_id'  => $_SESSION["ADMIN_ID"],
							'red_competitor_id' => $red_competitor_id,
							'red_news_id'    => $red_news_id,
							'blue_competitor_id' => $blue_competitor_id,
							'blue_news_id'    => $blue_news_id,
							'news_status' => $news_status,
							'quiz_status' => $quiz_status,
							'is_props' => $prop_status,
							'view_ranage'=>$view_ranage,
							'is_fast'=>$is_fast,
                                                        'company_id'=>$this->company_id,
//							'screen'=>$screen
					);
                                        $start_time=date('Y-m-d H:i',strtotime($start_time));
                                        switch($start_time){
                                            case $start_time > date('Y-m-d H:i');
                                            $param['status'] = 3; //未开始
                                            break;
                                            default :
                                            $param['status'] = 1; //已开始
                                        }  
					$result = $this->live->add($param);

					//来自新闻 则同时 添加直播的新闻
					if($add_from == 1){
						$news_id_add = time().$this->getRange();
						if($liveType == 1){
							$news_type = 9; //普通直播
						}else if($liveType == 2){
							$news_type = 10; //VR直播
						}else if($liveType == 3){
							$news_type = 11; //图文直播
						}else if($liveType == 4){
							$news_type = 12; //视频+图文
						}else if($liveType == 5){
							$news_type = 13; //VR+图文
						}

						$news_data = array(
							'news_id'      => $news_id_add,
							'title'   	   => $name,
							'cover_image'  => $image_url,
							'app_pub' 	   => 1,
							'weight'       => 70,
							'type'         => $news_type,
							'create_time'  => date('Y-m-d H:i:s', time()),
							'refresh_time' => time(),
							'live_id'      => $live_id
						);
						$news_data['column_id']    = isset($_GET["column_id"]) ? $_GET["column_id"] : '';
						$news_data['area_id']      = isset($_GET["area_id"]) ? $_GET["area_id"] : '';

						M("vrnews1.news")->add($news_data);
						$live_news_data['news_id'] = $news_id_add;
						$this->live->where('live_id = '.$live_id)->data($live_news_data)->save();
					}

					if($result){
//						if($liveType > 2) {
//							//添加 直播业务员
//							$live_admin_names = I("live_admin_names");
//							$live_admin_ids   = I("live_admin_ids");
//
//							$res_admin_names = explode(',', substr($live_admin_names, 0,-1));
//							$res_admin_ids   = explode(',', substr($live_admin_ids, 0,-1));
//
//							foreach ($res_admin_ids as $key=>$val){
//								$live_manages = array(
//									'live_id'=>$live_id,
//									'admin_id'=>$val,
//									'admin_name'=>$res_admin_names[$key],
//									'create_time'=>date('Y-m-d H:i:s'),
//								);
//								M("vrlive.live_manager")->add($live_manages);
//							}
//						}
						//如果是视频直播 或视频加图文 的快直播，添加 默认频道给指派的人 
//						if(in_array($liveType,array(1,4)) && $is_fast == 1){
//							$live_channel_res = intval(I("live_channel_res")[0]); //被指派人ID
//							//查询无输入流 频道
//							$channelList = $this->live_channel->getLiveChannelNoneList();
//							$chan_id = $channelList[0]['channel_id'];
//							if(mb_strlen($channelList[0]['channel_name']) > 8){
//								$chan_name = $channelList[0]['channel_name'];
//							}else{
//								$chan_name = '默认' . $channelList[0]['channel_name'];
//							}
//
//							//添加
//							$live_camera = array(
//								'live_id'       =>$live_id,
//								'signal_source' =>1,
//								'name'          =>$chan_name,
//								'source_id'     =>$chan_id,
//								'operator_id'   =>$live_channel_res,
//							);
//
//							$this->live_camera_angle->add($live_camera);
//						}
						
						//如果是图文直播在图文消息中添加一条信息
						if(in_array($liveType, array(3,4,5))){
							$compere = $this->live->getCompere($live_id);
							$date_time = $this->live->getDateTime($data);
							$msg_content = array(
								"msg_id"=>"0",
								"content"	=>$name."将于".$start_time."进行直播，敬请期待",
								"compere_id"=>$compere['creator_id'],//管理员编号
								"compere_name"	=>$compere['live_man_alias'],//"直播员别名",
								"compere_avatar"=>$compere['live_man_avatar_url'],//"直播员头像"
								"images_url"	=>"",   //图片集
								"videos_url"	=>"",//视频集合
								"video_thumbnails"	=>"",//视频封面图集合
								"on_list_user_info"	=>array(
									"user_username"	=>'',
									"user_id"		=>'',
									"user_content"	=>'',
									"msg_time"	=>date('H:i:s',time()),
									"msg_date"	=>date('Y-m-d',time())
								),
								"date_time" =>$date_time
							);
							$param = array(
								'live_id'=>$live_id,
								'create_time'=>date('Y-m-d H:i:s',time()),
								'pic_txt_content'=>$msg_content['content'],
								'content_type'=>'1',
								'sort_number'=>$this->getNextSortNumber(),
								'creator_id'=>$msg_content['compere_id'],
								'json_data'=>json_encode($msg_content),
							);
							$this->live_panel_manage->add($param);
						}
						
						
						//机位
						$angle_name_a = I("post.angle_name", '');
						$angle_channel_id_a = I("post.angle_channel_id", '');
						$angle_operator_id_a = I("post.angle_operator_id", '');
						$i = 0;
						foreach ($angle_name_a as $name){
							if(!empty($name)){
								$dataList[] = array(
										'live_id' => $live_id,
										'name' => $name,
										'source_id'    => $angle_channel_id_a[$i],
										'operator_id'  => $angle_operator_id_a[$i]
								);
							}
							$i = $i+1;
						}
						if(!empty($dataList)){
							$this->live_camera_angle->addAll($dataList);
						}
						//相关新闻
						$news_url_a = I("post.news_url", '');
						$news_weight_a = I("post.news_weight", '');
						if(1 == $news_status){
							$dataList = array();
							if('' != $news_url_a){
								$i = 0;
								foreach ($news_url_a as $url){ 
									if(!empty($url)){
										$a = $this->get_news_id($url);
								        $dataList[] = array(
								        		'live_id' => $live_id,
								        		'news_id' => $a['id'],
								        		'type'    => $a['type'],
								        		'weight'  => $news_weight_a[$i]
								        );
									}
							        $i = $i+1;
							    } 
							    if(!empty($dataList)){
							    	$this->live_news_relation->addAll($dataList);
							    }
							}
						}
						if(!in_array($liveType,array(3,4,5))) $this->live->update_live_category($live_id);  //更改直播类型
						if(!empty($_FILES['video1']['name']) || !empty($_FILES['video2']['name'])){
							$upload = new \Think\Upload();// 实例化上传类
							$upload->maxSize   =     899614161 ;// 设置附件上传大小
							$upload->exts      =     array('avi', 'mp4', 'rmvb', 'flv', 'asf', 'rm', '3gp', 'wmv', 'mpeg', 'mpg');// 设置附件上传类型
							$upload->rootPath  =     C('UPLOADPATH'); // 设置附件上传根目录
							$upload->savePath  =     ''; // 设置附件上传（子）目录
							
							// 上传文件
							$info = $upload->upload();
							//上传视频
							if(!empty($_FILES['video1']['name'])){
								$videoModel = new LiveVideoModel();
								$result1    = $videoModel->uploadVideo($info,$live_id,$is_vr1,1); //上传视频
							}
							
							if(!empty($result1)){  //添加视频
								$video1['live_id'] = $live_id;
								$video1['file_id'] = $result1;
								$video1['category'] = $is_vr1;
								$video1['type'] = 1;
								$video1['file_name'] = $_FILES['video1']['name'];
								$videoObj = new LiveVideoModel();
								$videoObj->add($video1);
							}
							
							if(!empty($_FILES['video2']['name'])){
								$videoModel = new LiveVideoModel();
								$result2    = $videoModel->uploadVideo($info,$live_id,$is_vr2,2); //上传视频
							}
								
							if(!empty($result2)){  //添加视频
								$video2['live_id'] = $live_id;
								$video2['file_id'] = $result2;
								$video2['category'] = $is_vr2;
								$video2['type']= 2;
								$video2['file_name'] = $_FILES['video2']['name'];
								$videoObj = new LiveVideoModel();
								$videoObj->add($video2);
							}
						}else{
							//添加手动填写的未开始视频信息
							if($file_id1 && $qcloud_file_name1){
					        	$videoModel = new LiveVideoModel();
					        	$video_list_data = $videoModel->get_video($qcloud_file_name1);
					        	if(!empty($video_list_data)){
					        		if($video_list_data['codeDesc'] == 'Success'){
					        			foreach($video_list_data['fileSet'] as $key=>$value){
					        				if($value['fileId'] == $file_id1){
					        					foreach($value['playSet'] as $key1=>$value1){
					        						if($value1['definition'] == '30'){
					        							$update_data['video_url'] = $value1['url'];
					        							$update_data['height'] = $value1['vheight'];
					        							$update_data['width'] = $value1['vwidth'];
					        							$update_data['size'] = '0';
					        						}
					        						 
					        						if($value1['definition'] == '20'){
					        							$update_data['video_url1'] = $value1['url'];
					        							$update_data['height1'] = $value1['vheight'];
					        							$update_data['width1'] = $value1['vwidth'];
					        							$update_data['size1'] = '0';
					        						}
					        						 
					        						if($value1['definition'] == '10'){
					        							$update_data['video_url2'] = $value1['url'];
					        							$update_data['height2'] = $value1['vheight'];
					        							$update_data['width2'] = $value1['vwidth'];
					        							$update_data['size2'] = '0';
					        						}
					        						 
					        					}
					        					$update_data['thumbnail_url'] = $value['image_url'];
					        				}
					        			}
					        			if(!empty($update_data)){
					        				$update_data['status'] = '2';
					        			}else{
					        				$update_data['status'] = '3';
					        			}
					        	
					        			$update_data['duration'] = $this->changeTimeType($value['duration']);
					        			$update_data['category'] = $is_vr1;
					        			$update_data['type'] = 1;
					        			$update_data['update_time'] = date('Y-m-d H:i:s',time());
					        			$update_data['live_id'] = $live_id;
					        			$update_data['file_id'] = $file_id1;
					        			 
					        		}
					        	}
					        	$videoObj = new LiveVideoModel();
					        	$videoObj->delete($file_id1);
					        	if($videoObj->add($update_data)){
					        		$url = '';
					        		if(!$url) $url = $update_data['video_url'];
					        		if(!$url) $url = $update_data['video_url1'];
					        		if(!$url) $url = $update_data['video_url2'];
					        		if($url){
					        			$data['befor_start_url'] = $url;
					        			$data['befor_video_category'] = $is_vr1;
					        			$this->live->where('live_id = '.$live_id)->data($data)->save();
					        		}
					        	}
					        	
						    }
						    
						    //添加手动填写的回放视频信息
						    if($file_id2 && $qcloud_file_name2){
						    	$videoModel = new LiveVideoModel();
						    	$video_list_data = $videoModel->get_video($qcloud_file_name2);
						    	if(!empty($video_list_data)){
						    		if($video_list_data['codeDesc'] == 'Success'){
						    			foreach($video_list_data['fileSet'] as $key=>$value){
						    				if($value['fileId'] == $file_id2){
						    					foreach($value['playSet'] as $key1=>$value1){
						    						if($value1['definition'] == '30'){
						    							$update_data['video_url'] = $value1['url'];
						    							$update_data['height'] = $value1['vheight'];
						    							$update_data['width'] = $value1['vwidth'];
						    							$update_data['size'] = '0';
						    						}
						    						 
						    						if($value1['definition'] == '20'){
						    							$update_data['video_url1'] = $value1['url'];
						    							$update_data['height1'] = $value1['vheight'];
						    							$update_data['width1'] = $value1['vwidth'];
						    							$update_data['size1'] = '0';
						    						}
						    						 
						    						if($value1['definition'] == '10'){
						    							$update_data['video_url2'] = $value1['url'];
						    							$update_data['height2'] = $value1['vheight'];
						    							$update_data['width2'] = $value1['vwidth'];
						    							$update_data['size2'] = '0';
						    						}
						    						 
						    					}
						    					$update_data['thumbnail_url'] = $value['image_url'];
						    				}
						    			}
						    			if(!empty($update_data)){
						    				$update_data['status'] = '2';
						    			}else{
						    				$update_data['status'] = '3';
						    			}
						    			 
						    			$update_data['duration'] = $this->changeTimeType($value['duration']);
						    			$update_data['category'] = $is_vr2;
						    			$update_data['type'] = 2;
						    			$update_data['update_time'] = date('Y-m-d H:i:s',time());
						    			$update_data['live_id'] = $live_id;
						    			$update_data['file_id'] = $file_id2;
						    
						    		}
						    	}
						    	$videoObj = new LiveVideoModel();
						    	$videoObj->delete($file_id2);
						    	if($videoObj->add($update_data)){
						    		$url = '';
						    		if(!$url) $url = $update_data['video_url'];
						    		if(!$url) $url = $update_data['video_url1'];
						    		if(!$url) $url = $update_data['video_url2'];
						    		if($url){
						    			$data['rever_url'] = $url;
						    			$data['rever_video_category'] = $is_vr2;
						    			$this->live->where('live_id = '.$live_id)->data($data)->save();
						    		}
						    	}
						    }
						    
						    
						}
//						$redis = new Redis();
//						$name = 'live_list_update';
//						$key = $redis->buildKey($name);
//						$redis->set_redis($key, time());
                        if($add_from == 1){
						        $this->success("添加成功！", U("Admin/News/index",array($id_type=>$id_val,'add_from'=>1)));
						}else{
						        $this->success("添加成功！", U("Admin/Live/index"));
						}
					}else{
						return $this->error('添加失败');
					}
				}else{
					return $this->error('创建融云聊天室失败，请联系系统管理员！');
				}
			}
		}
	}
	
	private function create_live_id(){
		return date('Y') . time() . rand(0000, 9999);
	}

	/**
	 * 创建融云聊天室
	 * @param $live_id
	 * @return mixed
	 */
	private function create_rcloud_chroom($live_id){
		$nonce = mt_rand();
		$timeStamp = time();
		$sign = sha1(C('ryAppSecret') . $nonce . $timeStamp);
		$header = array(
				'RC-App-Key:' . C('ryAppKey'),
				'RC-Nonce:' . $nonce,
				'RC-Timestamp:' . $timeStamp,
				'RC-Signature:' . $sign,
		);
		$data = 'chatroom[room_' . $live_id . ']=n'.$live_id;
		$result = $this->curl_http(C("ryApiUrl") . '/chatroom/create.json', $data, $header);
		return $result['code'];
	}
	/**
	 * 创建融云图文直播聊天室
	 * @param $live_id
	 * @return mixed
	 */
	private function create_rcloud_chroom_pic_txt($live_id){
		$nonce = mt_rand();
		$timeStamp = time();
		$sign = sha1(C('ryAppSecret') . $nonce . $timeStamp);
		$header = array(
				'RC-App-Key:' . C('ryAppKey'),
				'RC-Nonce:' . $nonce,
				'RC-Timestamp:' . $timeStamp,
				'RC-Signature:' . $sign,
		);
		$data = 'chatroom[room_' . $live_id . ']=ptn'.$live_id;
		$result = $this->curl_http(C("ryApiUrl") . '/chatroom/create.json', $data, $header);
		return $result['code'];
	}
	
	/**
	 * 获取专题id
	 * @param $news_url
	 * @return array
	 */
	private function get_news_id($news_url){
		$a = explode('&', htmlspecialchars_decode($news_url));
		$params = array();

		foreach ($a as $param){
			$item = explode('=', $param);
			$params[$item[0]] = $item[1];
		}
		return $params;
	}
	
	function edit(){				
		$live = $this->_get_live();
		$add_from  = I("get.add_from") ? I("get.add_from") : 0; //来源 1新闻
		$column_id = I("get.column_id") ? I("get.column_id") : '';
		$area_id   = I("get.area_id") ? I("get.area_id") : '';
		$live_id   = I("get.live_id") ? I("get.live_id") : '';
		$news_id   = I("get.news_id") ? I("get.news_id") : '';

		if($live['category'] > 2 || $live['category'] == 1) {
			$live_manager = M("vrlive.live_manager",null);
			$live_managers = $live_manager->field("admin_id,admin_name")->where("live_id = ".$live_id)->select();

			$admin_ids = '';
			$usernames = '';
			if($live_managers) {
				foreach ($live_managers as $key => $val) {
					$admin_ids .= $val['admin_id'].',';
					$usernames .= $val['admin_name'].',';
				}
				$admin_ids = substr($admin_ids,0,-1);
				$usernames = substr($usernames,0,-1);
			}

			if (empty($usernames)) {
				$arr_usernames = '';
			} else {
				$arr_usernames = explode(',', $usernames);
			}
			if (empty($admin_ids)) {
				$arr_admin_ids = '';
			} else {
				$arr_admin_ids = explode(',', $admin_ids);
			}

			//全部 管理员
			$admins = M("vradmin1.admin_user", null);
			$admin_infos = $admins
				->where("type = 2 and status = 1")
				->select();

			$this->assign("arr_admin_ids",$arr_admin_ids);
			$this->assign("arr_usernames", $arr_usernames);
			$this->assign("admin_infos", $admin_infos);
			$this->assign("admin_ids", $admin_ids);
			$this->assign("usernames", $usernames);
		}

		//如果是视频直播 或视频加图文 的快直播，显示 默认频道给指派的人
		if(in_array($live['category'],array(1,4)) && $live['is_fast'] == 1){
			$live_operator_info = $this->live_camera_angle->where('live_id = '.$live_id.' and status=1')->find();
			$live_operator_id = $live_operator_info['operator_id'];
			$this->assign("live_operator_id",$live_operator_id);
		}

		if($column_id){
			$id_type = "column_id";
			$id_val  = $column_id;
		}else{
			$id_type = "area_id";
			$id_val  = $area_id;
		}	
		
		$admin_id = $_SESSION['ADMIN_ID'];	

		$this->assign("add_from",$add_from);
		$this->assign("id_type",$id_type);
		$this->assign("id_val",$id_val);
		$this->assign("live_id",$live_id);
		$this->assign("news_id",$news_id);
		$this->assign("admin_id",$admin_id);

		$this->assign($live);
		$this->display();
	}
	
	function edit_post(){
		//接受手填视频信息
		$file_id1 =  I("file_id1");
		$qcloud_file_name1 =  I("qcloud_file_name1");
		$file_id2 =  I("file_id2");
		$qcloud_file_name2 =  I("qcloud_file_name2");

		$add_from    = I("get.add_from") ? I("get.add_from") : 0; //来源 1新闻
		$column_id   = I("get.column_id") ? I("get.column_id") : '';
		$area_id     = I("get.area_id") ? I("get.area_id") : '';
		$get_live_id = I("get.live_id") ? I("get.live_id") : '';
		$news_id     = I("get.news_id") ? I("get.news_id") : '';
//		$screen    = I("screen") ? I("screen") : 0; //画面方向 默认0横屏

		if($column_id){
			$id_type = "column_id";
			$id_val  = $column_id;
		}else{
			$id_type = "area_id";
			$id_val  = $area_id;
		}

		$liveType = I("post.liveType", '');
		if(empty($liveType) && $add_from == 0){
			return $this->error("请选择直播类型！");
		}
		
		$quiz_status = I("post.quiz_status");
		$prop_status = I("post.prop_status");
		$name = I("post.name", '');
		if(empty($name)){
			return $this->error("直播名称不能为空！");
		}
		
		$live_man_cate = I("post.live_man_cate", '');
		$live_man_alias = I("post.live_man_alias", '');
		if(in_array($liveType, array(3,4,5))){
			if(empty($live_man_cate)){
				return $this->error("请填写直播员类别！");
			}
			if(empty($live_man_alias)){
				return $this->error("请填写直播员别名！");
			}
//			if(I("live_admin_ids") == ','){
//				return $this->error("请选择直播业务员");
//			}
			$avatar_file_id_hidden = I("avatar_file_id_hidden");
			if(empty($avatar_file_id_hidden)){
				if(!isset($_FILES['avatar_file'])){
					return $this->error("请上传直播员头像！");
				}
			}
//			if($liveType == 4){
//				//查看 推流业务员
//				$if_operator_info = $this->live_camera_angle->where('live_id = '.$get_live_id.' and status=1')->select();
//				if($if_operator_info){
//					//对比
//					$if_manager_ids = array_column($if_operator_info, 'operator_id');
//					$if_id_arr = explode(',', substr(I("live_admin_ids"), 0,-1));
//					$if_cou = count(array_intersect($if_id_arr, $if_manager_ids));
//					if($if_cou > 0){
//						return $this->error("两种业务员 不能重复");
//					}
//				}
//			}

		}
		$is_fast = 0;
		if(I('fast_live_status') == 'on'){
			$is_fast = 1;
		}
//		if(in_array($liveType,array(1,4)) && $is_fast == 1) {
//			if (!I("live_channel_res")) {
//				return $this->error("请选择 直播推流业务员");
//			}
//			if($liveType == 4){
//				$admin_id_arr = explode(',', substr(I("live_admin_ids"), 0,-1));
//				$live_admin_val = intval(I("live_channel_res")[0]);
//				if(in_array($live_admin_val, $admin_id_arr)){
//					return $this->error("两种业务员 不能重复");
//				}
//			}
//		}
		
		$weight = I("post.weight", 70);
			
		if (!preg_match('/^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/', $weight)) {
			return $this->error("权重必须为0到255的数字！");
		}
		
		$start_time = I("post.start_time", '');
		if(empty($start_time)){
			return $this->error("开始时间不能为空！");
		}

		$live_id = I("post.live_id");
		$sel_live = $this->live->where(array('live_id'=>$live_id))->find();
		if($add_from == 1 && !empty($sel_live['news_id']) && $liveType != $sel_live['category']){
			//修改 对应新闻 的类型
			M("vrnews1.news")->where(['news_id'=>$sel_live['news_id']])->save(array('type',$liveType));
		}

		
		$weight = I("post.weight", 70);
		
		$type = I("post.type", 1);
		$red_competitor_id = I("post.red_competitor_id", 0);
		$red_news_url = I("post.red_news_url", '');
		if('' == $red_news_url){
			$red_news_id = 0;
		}else{
			$red_news_id = $this->get_news_id($red_news_url)['id'];
		}
		$blue_competitor_id = I("post.blue_competitor_id", 0);
		$blue_news_url = I("post.blue_news_url", '');
		if('' == $blue_news_url){
			$blue_news_id = 0;
		}else{
			$blue_news_id = $this->get_news_id($blue_news_url)['id'];
		}
		$news_status = I("post.news_status", 0);
		
		$introduction_status = I("post.introduction_status", 0);
		
		$title = I("post.title", '');
		$introduction = I("post.introduction", '');

		//获取未直播、直播中、直播结束三状态下访问直播时的设置的随机增加访问量数的值
		$no_start_view_ranage_from = I("post.no_start_view_ranage_from", '5');
		$no_start_view_ranage_to = I("post.no_start_view_ranage_to", '10');
		$loading_view_ranage_from = I("post.loading_view_ranage_from", '1');
		$loading_view_ranage_to = I("post.loading_view_ranage_to", '20');
		$end_view_ranage_from = I("post.end_view_ranage_from", '1');
		$end_view_ranage_to = I("post.end_view_ranage_to", '5');
		$view_ranage = $no_start_view_ranage_from.'-'.$no_start_view_ranage_to.'|'.$loading_view_ranage_from.'-'.$loading_view_ranage_to.'|'.$end_view_ranage_from.'-'.$end_view_ranage_to;
		
		$remark = I("post.remark", '');
		
		$upload = new \Think\Upload();// 实例化上传类
		$upload->maxSize   =     59614161 ;// 设置附件上传大小
		$upload->exts      =     array('jpeg', 'jpg', 'bmp', 'png');// 设置附件上传类型
		$upload->rootPath  =     C('UPLOADPATH'); // 设置附件上传根目录
		$upload->savePath  =     ''; // 设置附件上传（子）目录
	
		$image_url = '';	
		$live_man_avatar_url = '';
		if(!empty($_FILES)){
			// 上传封面文件
			$info = $upload->upload();
			if(!$info) {// 上传错误提示错误信息
				$this->error($upload->getError());
			}else{
				if(isset($info['imageFile'])){
					$cname = C('UPLOADPATH').$info['imageFile']['savepath'].$info['imageFile']['savename'];
					$fileName = 'lv'.time().$info['imageFile']['savename'];  // 自定义文件名
					$uploadRet = ImageV2::upload($cname, Conf::BUCKET, $fileName);
					\Think\Log::record('上传封面万象优图返回：'.json_encode($uploadRet), 'INFO');
					
					if($uploadRet['httpcode'] == 200){
						$image_url = $uploadRet['data']['downloadUrl'];
					}else{
						return $this->error('封面图片上传腾讯云失败，请联系系统管理员！');
					}
					//删除本地文件
					unlink($cname);
				}
				
				if(isset($info['avatar_file'])){
					$cname2 = C('UPLOADPATH').$info['avatar_file']['savepath'].$info['avatar_file']['savename'];
					$fileName2 = 'lv'.time().$info['avatar_file']['savename'];  // 自定义文件名
					$uploadRet2 = ImageV2::upload($cname2, Conf::BUCKET, $fileName2);
					\Think\Log::record('上传头像万象优图返回：'.json_encode($uploadRet2), 'INFO');
					
					if($uploadRet2['httpcode'] == 200){
						$live_man_avatar_url = $uploadRet2['data']['downloadUrl'];
					}else{
						return $this->error('头像图片上传腾讯云失败，请联系系统管理员！');
					}
					//删除本地文件
					unlink($cname2);
				}
					
			}	
		}


// 		if(!empty($_FILES) && isset($_FILES['avatar_file'])){
// 			// 上传直播员头像文件
// 			$info = $upload->upload();
// 			if(!$info) {// 上传错误提示错误信息
// 				$this->error($upload->getError());
// 			}else{
// 				$cname2 = C('UPLOADPATH').$info['avatar_file']['savepath'].$info['avatar_file']['savename'];
// 				$fileName2 = 'lv'.time().$info['avatar_file']['savename'];  // 自定义文件名
// 				$uploadRet2 = ImageV2::upload($cname2, Conf::BUCKET, $fileName2);
// 				\Think\Log::record('上传头像万象优图返回：'.json_encode($uploadRet2), 'INFO');
		
// 				if($uploadRet2['httpcode'] == 200){					
// 					$live_man_avatar_url = $uploadRet2['data']['downloadUrl'];
// 				}else{
// 					return $this->error('头像图片上传腾讯云失败，请联系系统管理员！');
// 				}
// 			}
// 			//删除本地文件
// 			unlink($cname2);
// 		}		
		
		$is_vr1 = I("post.is_vr1", '1');
		$is_vr2 = I("post.is_vr2", '1');
			
		$update_time = date('Y-m-d H:i:s');
		$param = array(
				'category'=>$liveType,
				'live_man_cate'=>$live_man_cate,
				'live_man_alias'=>$live_man_alias,				
				'name'	  => $name,
				'weight'  => $weight,
				'start_time' => $start_time,
				'introduction_status' => $introduction_status,
				'title'   => $title,
				'introduction' => $introduction,
				'remark'    => $remark,
				'type'    => $type,
				'befor_video_category' =>$is_vr1,
				'rever_video_category' =>$is_vr2,
				'update_time' => $update_time,
				'creator_id'  => $_SESSION["ADMIN_ID"],
				'red_competitor_id' => $red_competitor_id,
				'red_news_id'    => $red_news_id,
				'blue_competitor_id' => $blue_competitor_id,
				'blue_news_id'    => $blue_news_id,
				'news_status' => $news_status,
				'quiz_status' => $quiz_status,
				'is_props' => $prop_status,
				'view_ranage'=>$view_ranage,
				'is_fast'=>$is_fast,
//				'screen'=>$screen
		);
		if(!empty($image_url)){
			$param['image_url'] = $image_url;
		}
		if(!empty($live_man_avatar_url)){
			$param['live_man_avatar_url'] = $live_man_avatar_url;
		}

		//修改 直播时间 更改直播状态
                $start_time=date('Y-m-d H:i',strtotime($start_time));
                switch($start_time){
                    case $start_time > date('Y-m-d H:i');
                    $param['status'] = 3; //未开始
                    break;
                    default :
                    $param['status'] = 1; //已开始
                } 

		$result = $this->live->where(array('live_id'=>$live_id))->save($param);

		if($result){
//			if(in_array($liveType,array(3,4,5))){
//				//添加 直播业务员
//				$live_admin_names = I("live_admin_names");
//				$live_admin_ids   = I("live_admin_ids");
//
//				$res_admin_names = explode(',', substr($live_admin_names, 0,-1));
//				$res_admin_ids   = explode(',', substr($live_admin_ids, 0,-1));
//
//				//查看 之前存储 业务员信息
//				$live_manager = M("vrlive.live_manager",null);
//				//查看 并对比是否有改动
//				$live_manager_res = $live_manager->where("live_id = ".$get_live_id)->select();
//				$live_manager_ids = array_column($live_manager_res, 'admin_id');
//				$admin_ids_cou = count($res_admin_ids);
//				$manager_ids_cou = count($live_manager_ids);
//				$sect_cou = count(array_intersect($res_admin_ids, $live_manager_ids));
//
//				if(($admin_ids_cou != $manager_ids_cou) || ($admin_ids_cou != $sect_cou)){
//					//删除 并添加新的指派人
//					$live_manager->where("live_id = ".$get_live_id)->delete();
//
//					foreach ($res_admin_ids as $key=>$val){
//						$live_manages = array(
//							'live_id' => $get_live_id,
//							'admin_id' => $val,
//							'admin_name' => $res_admin_names[$key],
//							'create_time' => date('Y-m-d H:i:s'),
//						);
//						M("vrlive.live_manager")->add($live_manages);
//					}
//				}
//			}

			//如果是视频直播 或视频加图文 的快直播，添加 默认频道给指派的人
//			if(in_array($liveType,array(1,4)) && $is_fast == 1){
//				$live_channel_res = intval(I("live_channel_res")[0]); //被指派人ID
//				//查看是否修改了原指派人
//				$live_operator_info = $this->live_camera_angle->where('live_id = '.$live_id.' and status=1')->find();
//				if($live_operator_info['operator_id'] != $live_channel_res){
//					//修改指派人
//					//查询无输入流 频道
//					$channelList = $this->live_channel->getLiveChannelNoneList();
//					$chan_id = $channelList[0]['channel_id'];
//					if(mb_strlen($channelList[0]['channel_name']) > 8){
//						$chan_name = $channelList[0]['channel_name'];
//					}else{
//						$chan_name = '默认' . $channelList[0]['channel_name'];
//					}
//
//					$live_camera = array(
//						'live_id'       =>$live_id,
//						'signal_source' =>1,
//						'name'          =>$chan_name,
//						'source_id'     =>$chan_id,
//						'operator_id'   =>$live_channel_res,
//					);
//					if(!$live_operator_info['operator_id']){
//						M("vrlive.live_camera_angle")->add($live_camera);
//					}else {
//						$this->live_camera_angle
//							->where('camera_id = ' . $live_operator_info['camera_id'])
//							->data($live_camera)->save();
//					}
//				}
//			}

//			//机位
//			$angle_name_a = I("post.angle_name", '');
//			//$angle_channel_id_a = I("post.angle_channel_id", '');
//			$source_id_a = I("post.source_id", '');
//			$angle_operator_id_a = I("post.angle_operator_id", '');
//			$angle_name_status_a = I("post.angle_name_status", '');
//			$signal_source_a = I("post.signal_source", '');
//			$i = 0;
//			foreach ($angle_name_a as $name){
//				if(!empty($name)){
//					$dataList[] = array(
//							'live_id' => $live_id,
//							'name' => $name,
//							'signal_source'=>$signal_source_a[$i],
//							'source_id'    => $source_id_a[$i],
//							'operator_id'  => $angle_operator_id_a[$i],
//							'status'=>$angle_name_status_a[$i]
//					);
//				}
//				$i = $i+1;
//			}
//			$this->live_camera_angle->where(array('live_id'=>$live_id))->delete();
//			if(!empty($dataList)){
//				$this->live_camera_angle->addAll($dataList);
//			}
			//相关新闻
			$news_url_a = I("post.news_url", '');
			$news_weight_a = I("post.news_weight", '');
			if(1 == $news_status){
				$dataList = array();
				if('' != $news_url_a){
					$i = 0;
					foreach ($news_url_a as $url){ 
						if(!empty($url)){
							$a = $this->get_news_id($url);
					        $dataList[] = array(
					        		'live_id' => $live_id,
					        		'news_id' => $a['id'],
					        		'type'    => $a['type'],
					        		'weight'  => $news_weight_a[$i]
					        );
						}
				        $i = $i+1;
				    } 
				    $this->live_news_relation->where(array('live_id'=>$live_id))->delete();
				    if(!empty($dataList)){
				    	$this->live_news_relation->addAll($dataList);
				    }
				}
			}
			if(!in_array($liveType, array(3,4,5))) $this->live->update_live_category($live_id);
			
			if(!empty($_FILES['video1']['name']) || !empty($_FILES['video2']['name'])){
				$upload = new \Think\Upload();// 实例化上传类
				$upload->maxSize   =     899614161 ;// 设置附件上传大小
				$upload->exts      =     array('avi', 'mp4', 'rmvb', 'flv', 'asf', 'rm', '3gp', 'wmv', 'mpeg', 'mpg');// 设置附件上传类型
				$upload->rootPath  =     C('UPLOADPATH'); // 设置附件上传根目录
				$upload->savePath  =     ''; // 设置附件上传（子）目录
				
				// 上传文件
				$info = $upload->upload();
				//上传视频
				if(!empty($_FILES['video1']['name'])){
					$videoModel = new LiveVideoModel();
					$result1    = $videoModel->uploadVideo($info, $live_id,$is_vr1,1); //上传视频
				}
				
				if(!empty($result1)){  //添加视频
					$video1['live_id'] = $live_id;
					$video1['file_id'] = $result1;
					$video1['category'] = $is_vr1;
					$video1['type'] = 1;
					$video1['file_name'] = $_FILES['video1']['name'];
					$videoObj = new LiveVideoModel();
					//删除视频
					$videoObj->where(array('live_id'=>$live_id,'type'=>1))->delete();
					$videoObj->add($video1);
				}
				
				if(!empty($_FILES['video2']['name'])){
					$videoModel = new LiveVideoModel();
					$result2 = $videoModel->uploadVideo($info, $live_id,$is_vr2,2); //上传视频
				}
					
				if(!empty($result2)){  //添加视频
					$video2['live_id'] = $live_id;
					$video2['file_id'] = $result2;
					$video2['category'] = $is_vr2;
					$video2['type'] = 2;
					$video2['file_name'] = $_FILES['video2']['name'];
					$videoObj = new LiveVideoModel();
					//删除视频
					$videoObj->where(array('live_id'=>$live_id,'type'=>2))->delete();
					$videoObj->add($video2);
				}
			}else{
				//添加手动填写的未开始视频信息
				if($file_id1 && $qcloud_file_name1){
		        	$videoModel = new LiveVideoModel();
		        	$video_list_data = $videoModel->get_video($qcloud_file_name1);
		        	if(!empty($video_list_data)){
		        		if($video_list_data['codeDesc'] == 'Success'){
		        			foreach($video_list_data['fileSet'] as $key=>$value){
		        				if($value['fileId'] == $file_id1){
		        					foreach($value['playSet'] as $key1=>$value1){
		        						if($value1['definition'] == '30'){
		        							$update_data['video_url'] = $value1['url'];
		        							$update_data['height'] = $value1['vheight'];
		        							$update_data['width'] = $value1['vwidth'];
		        							$update_data['size'] = '0';
		        						}
		        						 
		        						if($value1['definition'] == '20'){
		        							$update_data['video_url1'] = $value1['url'];
		        							$update_data['height1'] = $value1['vheight'];
		        							$update_data['width1'] = $value1['vwidth'];
		        							$update_data['size1'] = '0';
		        						}
		        						 
		        						if($value1['definition'] == '10'){
		        							$update_data['video_url2'] = $value1['url'];
		        							$update_data['height2'] = $value1['vheight'];
		        							$update_data['width2'] = $value1['vwidth'];
		        							$update_data['size2'] = '0';
		        						}
		        						 
		        					}
		        					$update_data['thumbnail_url'] = $value['image_url'];
		        				}
		        			}
		        			if(!empty($update_data)){
		        				$update_data['status'] = '2';
		        			}else{
		        				$update_data['status'] = '3';
		        			}
		        	
		        			$update_data['duration'] = $this->changeTimeType($value['duration']);
		        			$update_data['category'] = $is_vr1;
		        			$update_data['type'] = 1;
		        			$update_data['update_time'] = date('Y-m-d H:i:s',time());
		        			$update_data['live_id'] = $live_id;
		        			$update_data['file_id'] = $file_id1;
		        			 
		        		}
		        	}
		        	$videoObj = new LiveVideoModel();
		        	$videoObj->delete($file_id1);
		        	if($videoObj->add($update_data)){
		        		$url = '';
		        		if(!$url) $url = $update_data['video_url'];
		        		if(!$url) $url = $update_data['video_url1'];
		        		if(!$url) $url = $update_data['video_url2'];
		        		if($url){
		        			$data['befor_start_url'] = $url;
		        			$data['befor_video_category'] = $is_vr1;
		        			$this->live->where('live_id = '.$live_id)->data($data)->save();
		        		}
		        	}
		        	
			    }
			    
			    //添加手动填写的回放视频信息
			    if($file_id2 && $qcloud_file_name2){
			    	$videoModel = new LiveVideoModel();
			    	$video_list_data = $videoModel->get_video($qcloud_file_name2);
			    	if(!empty($video_list_data)){
			    		if($video_list_data['codeDesc'] == 'Success'){
			    			foreach($video_list_data['fileSet'] as $key=>$value){
			    				if($value['fileId'] == $file_id2){
			    					foreach($value['playSet'] as $key1=>$value1){
			    						if($value1['definition'] == '30'){
			    							$update_data['video_url'] = $value1['url'];
			    							$update_data['height'] = $value1['vheight'];
			    							$update_data['width'] = $value1['vwidth'];
			    							$update_data['size'] = '0';
			    						}
			    						 
			    						if($value1['definition'] == '20'){
			    							$update_data['video_url1'] = $value1['url'];
			    							$update_data['height1'] = $value1['vheight'];
			    							$update_data['width1'] = $value1['vwidth'];
			    							$update_data['size1'] = '0';
			    						}
			    						 
			    						if($value1['definition'] == '10'){
			    							$update_data['video_url2'] = $value1['url'];
			    							$update_data['height2'] = $value1['vheight'];
			    							$update_data['width2'] = $value1['vwidth'];
			    							$update_data['size2'] = '0';
			    						}
			    						 
			    					}
			    					$update_data['thumbnail_url'] = $value['image_url'];
			    				}
			    			}
			    			if(!empty($update_data)){
			    				$update_data['status'] = '2';
			    			}else{
			    				$update_data['status'] = '3';
			    			}
			    			 
			    			$update_data['duration'] = $this->changeTimeType($value['duration']);
			    			$update_data['category'] = $is_vr2;
			    			$update_data['type'] = 2;
			    			$update_data['update_time'] = date('Y-m-d H:i:s',time());
			    			$update_data['live_id'] = $live_id;
			    			$update_data['file_id'] = $file_id2;
			    
			    		}
			    	}
			    	$videoObj = new LiveVideoModel();
			    	$videoObj->delete($file_id2);
			    	if($videoObj->add($update_data)){
			    		$url = '';
			    		if(!$url) $url = $update_data['video_url'];
			    		if(!$url) $url = $update_data['video_url1'];
			    		if(!$url) $url = $update_data['video_url2'];
			    		if($url){
			    			$data['rever_url'] = $url;
			    			$data['rever_video_category'] = $is_vr2;
			    			$this->live->where('live_id = '.$live_id)->data($data)->save();
			    		}
			    	}
			    }
			    
			    
			}
//			$redis = new Redis();
//			$name = 'live_list_update';
//			$key = $redis->buildKey($name);
//			$redis->set_redis($key, time());
			if($add_from == 1){
				$this->success("修改成功！", U('Admin/live/edit',array('live_id'=>$get_live_id,'news_id'=>$news_id,$id_type=>$id_val,'add_from'=>1)));
			}else{
				$this->success("修改成功！", U("Admin/Live/index"));
			}
		}else{
			return $this->error('修改失败');
		}
	}
	
	function get_competitor(){
		$red_competitor_id = I("get.red_competitor_id");
		$blue_competitor_id = I("get.blue_competitor_id");
		$red = $this->live_competitor->find($red_competitor_id);
		$blue = $this->live_competitor->find($blue_competitor_id);
		$data = array('red'=>$red,'blue'=>$blue);
		$this->success($data);
	}
	
	function delete(){
		$live_id = I("get.live_id", 0);
		$status = 0;
	    $postData = array(
			'status'=>$status
		);
		$result = $this->live->where(array('live_id'=>$live_id))->save($postData);
		if($result){
//			$redis = new Redis();
//			$name = 'live_list_update';
//			$key = $redis->buildKey($name);
//			$redis->set_redis($key, time());
			$this->success("删除成功！", U("Admin/Live/index"));
		}else{
			return $this->error("删除失败！");
		}
	}
	
	function view(){
		$live = $this->_get_live();
		$this->assign($live);
		$this->display();
	}
	
	private function _get_live(){
		$live_id = I("get.live_id");		
		//查询频道
		$channelList = $this->live_channel->getLiveChannelList();
		//查询选手
		$competitorList = $this->live_competitor->getLiveCompetitorList();
		//查询机位
		$angleList = $this->live_camera_angle->get_camera_angle_list($live_id);
		if(!$angleList || empty($angleList)){
			$angleList = array();
		}
		//查询相关新闻
		$newsList = $this->live_news_relation->get_news_relation_list($live_id);
		if(!$newsList || empty($newsList)){
			$newsList = array();
		}
		//查询相关视频
		$befor_start_info = $this->live_video->where('live_id ='.$live_id.' and type=1')->find();
		$rever_info = $this->live_video->where('live_id ='.$live_id.' and type=2')->find();
		
		$this->assign("befor_start_info", $befor_start_info);
		$this->assign("rever_info", $rever_info);
		$this->assign("channelList", $channelList);
		$this->assign("competitorList", $competitorList);
		$this->assign("angleList", json_encode($angleList, JSON_UNESCAPED_UNICODE));

		//直播类型 Tah 20161208，新增字段
		//alter table live add live_type tinyint(4) default '0' COMMENT '直播类型：0：表示未设置直播类型,请选择；1视频直播；2VR直播;3图文直播'
 		$liveType = array("0"=>"请选择","1"=>"视频直播","2"=>"VR直播","3"=>"图文直播","4"=>"视频加图文直播","5"=>"VR加图文直播");		
		$this->assign("liveType",$liveType);

		//$this->assign("newsList", json_encode($newsList, JSON_UNESCAPED_UNICODE));
		$this->assign("newsList", $newsList);
		$live = $this->live->where(array('live_id'=>$live_id))->find();
		
		$view_range_list = array();
		if($live['view_ranage']){
			$view_range_list = explode('|', $live['view_ranage']);
		}
		$this->assign('view_range_list',$view_range_list);
		
		if($live && 0 != $live['red_news_id']){
			$live['red_news_url'] = 'id='.$live['red_news_id'].'&type=news';
		}
		if($live && 0 != $live['blue_news_id']){
			$live['blue_news_url'] = 'id='.$live['blue_news_id'].'&type=news';
		}
		if (empty($live['live_man_avatar'])){
			$live['live_man_avatar'] = 'avatar/default.png';
		}
		return $live;
	}
	
	//Tah 20161208
	function live_panel(){
		$live_id = I("get.live_id");
		$add_from = I("get.add_from") ? I("get.add_from") : 0;

		//获取融云token，供图文直播聊天室使用
		$admin = $this->admin_user_rcloud_token->find($_SESSION["ADMIN_ID"]);
		if(null == $admin || empty($admin)){
			$rcloud_token = $this->get_rcloud_token('ad_'.$_SESSION["ADMIN_ID"]);
			//创建token
			$data = array(
					'admin_id'=>$_SESSION["ADMIN_ID"],
					'rcloud_token'=>$rcloud_token
			);
			$this->admin_user_rcloud_token->add($data);
		}else{
			$rcloud_token = $admin['rcloud_token'];
		}		
		$this->assign('rcloud_token', $rcloud_token);
		$this->assign('ryAppKey', C('ryAppKey'));
		$this->assign('chatRoomId', "ptroom_$live_id");
		
		
		$list = $this->live->where('live_id = '.$live_id)->find();
		$this->assign("add_from",$add_from);
		$this->assign('live_id', $live_id);
		$this->assign('data', $list);
		$this->display();		
	}
	
	
	//Tah 20161208//用来测试用的另一个人
	//http://www.vradmin.com/index.php?g=Admin&m=Live&a=live_panel&live_id=201614823916413002
	//http://www.vradmin.com/index.php?g=Admin&m=Live&a=another_one&live_id=201614823916413002
	function another_one(){
		$live_id = I("get.live_id");
	
		//获取融云token，供图文直播聊天室使用
		$admin = $this->admin_user_rcloud_token->find(18);
		if(null == $admin || empty($admin)){
			$rcloud_token = $this->get_rcloud_token('ad_18');
			//创建token
			$data = array(
					'admin_id'=>18,
					'rcloud_token'=>$rcloud_token
			);
			$this->admin_user_rcloud_token->add($data);
		}else{
			$rcloud_token = $admin['rcloud_token'];
		}
		$this->assign('rcloud_token', $rcloud_token);
		$this->assign('ryAppKey', C('ryAppKey'));
		$this->assign('chatRoomId', "ptroom_$live_id");

		$list = $this->live->where('live_id = '.$live_id)->find();
		$this->assign('live_id', $live_id);
		$this->assign('data', $list);
		$this->display('live_panel');
	}
	
	
	//Tah 20161222加入图文直播聊天室
	function live_panel_join_ptchatroom($userId,$live_id){
		$nonce = mt_rand();
		$timeStamp = time();
		$sign = sha1(C('ryAppSecret') . $nonce . $timeStamp);
		$header = array(
				'RC-App-Key:' . C('ryAppKey'),
				'RC-Nonce:' . $nonce,
				'RC-Timestamp:' . $timeStamp,
				'RC-Signature:' . $sign,
		);
		$data = "userId=$userId&chatroomId=ptroom_$live_id";
		$result = $this->curl_http(C("ryApiUrl") . '/chatroom/join.json', $data, $header);
		return $result['code']==200;
	}
	
	function live_refresh_panel(){//图文消息面板的刷新按钮事件相应代码
		$nonce = mt_rand();
		$timeStamp = time();
		$sign = sha1(C('ryAppSecret') . $nonce . $timeStamp);
		$header = array(
				'RC-App-Key:' . C('ryAppKey'),
				'RC-Nonce:' . $nonce,
				'RC-Timestamp:' . $timeStamp,
				'RC-Signature:' . $sign,
		);		
		
		$data = "date=2016122215";
		$result = $this->curl_http(C("ryApiUrl") . '/message/history.json', $data, $header);
		if ($result['code']==200){
			$ret=array('code'=>200,'msg'=>'ok');
			echo json_encode($result);
		}
		else
		{
			$ret=array('code'=>200,'msg'=>'no');
			echo json_encode($ret);
		}	
							
		
	}
	//Tah 20161222推送消息到融云
	function live_panel_send_ptmessage($msg_content,$live_id,$fromUserId){
		$nonce = mt_rand();
		$timeStamp = time();
		$sign = sha1(C('ryAppSecret') . $nonce . $timeStamp);
		$header = array(
				'RC-App-Key:' . C('ryAppKey'),
				'RC-Nonce:' . $nonce,
				'RC-Timestamp:' . $timeStamp,
				'RC-Signature:' . $sign,
		);	
		$data = "content=$msg_content&fromUserId=$fromUserId&toChatroomId=ptroom_$live_id&objectName=RC:TxtMsg";
		
		$result = $this->curl_http(C("ryApiUrl") . '/message/chatroom/publish.json', $data, $header);
		return $result['code']==200;
	}
		
	
	//返回live_panel_send_ptmessage函数中的$msg_content部分
	function getPushDataForRongYun($data){
		/*
		$msg_content = array(
								"content"	=>"你好,我是图文消息文本！",
								"extra"		=>array(
														"compere"	=>array(
																			"id"	=>"直播员ID",
																			"name"	=>"直播员别名",
																			"avatar"=>"直播员头像"
																			),
														"image_url"	=>array("image_url1","image_url2","image_url3"),
														"video_url"	=>"",
														"user_info"	=>array(
																			"user_avatar"	=>"聊天室用户头像",
																			"user_username"	=>"聊天室用户姓名",
																			"user_id"		=>"聊天室用户ID",
																			"user_content"	=>"聊天室用户留言",
																			"msg_time"	=>"聊天室用户留言时间,如十二点零六：12:06",
																			"msg_date"	=>"聊天室用户留言日期，如2016年12月22日：20161222"
																			)														
													)
							);
		*/

		$compere = $this->live->getCompere($data['live_id']);
		$images = $this->live->getLivePanelImages($data['live_id']);
		//$videos = $this->live->getLivePanelVideos($data['live_id']);
		$user_info = $this->live->getToListUserInfo($data['msg_id']);
		$msg_content = array(
								"content"	=>$data['content'],
								"extra"		=>array(
														"compere"	=>array(
																			"id"	=>$compere['creator_id'],//管理员编号
																			"name"	=>$compere['live_man_alias'],//"直播员别名",
																			"avatar"=>$compere['live_man_avatar_url'],//"直播员头像"
																			),
														"images_url"	=>$images,   //图片集
														"videos_url"	=>$data['videos'],//视频集合
														"user_info"	=>$user_info //上榜用户信息											
													)
							); 
		return json_encode($msg_content);
	}
	//Tah 20161213直播面板的保存按钮的事件
	function live_update(){
		if (IS_POST) {			
			$data = $_POST["data"];
			$data=json_decode($data,true);
			$live_id = $data['live_id'];
			$userId = $_SESSION["ADMIN_ID"];//更新图文消息的管理员
			$data['creator_id']  = $userId;			
			$ret = $this->live->Live_Update_Pic_Txt($data);
			if ($data['opt_type']!=2)//<!-- opt_type:1(浏览状态，新增状态）；2（编辑状态）；3：（上榜状态） -->
			{				
				if ($this->live_panel_join_ptchatroom("ad_$userId",$live_id)){//加入聊天室
				  if ($this->live_panel_send_ptmessage($this->getPushDataForRongYun($data),$live_id,$userId)){//发送聊天室消息
				  	$ret['msg'] .='，消息成功推送到融云！';
				  }	
				  else 
				  {$ret['msg'] .='，消息推送融云失败！';}
				}
				else
				{
					$ret['msg'] .='，加入图文直播聊天室失败，尚未推送图文消息！';					
				}				
			}
						
			/*
			//notifyUrl='www.vradmin.com/index.php?g=api&m=video&a=callback&type=1&is_vr=0&key=b6589fc6ab0dc82cf12099d1c2d40ab994e8410c'
			$fileInfo = array('tmp_name'=>'D:\Workspace\phpStudy\WWW\lanxiangjiao.mp4');
			$newsModel = new NewsVideoModel();
			$fileId    = $newsModel->uploadLivePanelVideo($fileInfo); //上传视频
			writelog('filed',$fileId);
			*/
			echo json_encode($ret);
		}		
	}
	
	function sign($array){
		if(!empty($array['sign'])){
			unset($array['sign']);
		}
		ksort($array);
		$string="";
		while (list($key, $val) = each($array)){
			$string .= $key.'='.$val.'&';
		}
		$string = rtrim($string, '&');
		//        echo md5($string);exit();
		return md5($string);
	}
	
	function make_sign_string(){
		$newarray=array();
		$timestamp = time();
		$array['timestamp'] = $timestamp;
		$array['app_key']   = 'helloword';
		$array['unique']    = 'xinhuiwen,fighting!';
		reset($array);
		
		while(list($key,$val) = each($array)){	
			$encode = '';
			$encode = mb_detect_encoding($array[$key], array("ASCII","UTF-8","GB2312","GBK"));
			//iconv($array[$key], "UTF-8", $encode);
			$newarray[$key] = $array[$key];
			
		}
		$sign = $this->sign($newarray); 
		return "timestamp=$timestamp&app_key=".$array['app_key']."&unique=".$array['unique']."&sign=$sign";
	}
	//Tah 20161214
	//http://www.vradmin.com/index.php?g=Admin&m=Live&a=get_live_panel&live_id=1&timestamp=1481705515&app_key=helloword&unique=xinhuiwen%2Cfighting!&sign=baaf9e034864ae896952b589a4ec42ed&token=dc5b4a419b4c23453f9ec166356542e4cd7c9987
	//获取某直播面板的内容列表
	function get_live_panel(){		
		//$token = !empty($_REQUEST['token']) ? $_REQUEST['token'] : '';
		$live_id = !empty($_REQUEST['live_id']) ? $_REQUEST['live_id'] : '0';//图文直播编号
        $msg_id = !empty($_REQUEST['msg_id']) ? $_REQUEST['msg_id'] : '0';//图文直播中的某一消息的编号,如果指定了值，则只返回该消息的内容而非该live_id的全部msg_id的内容
        $file_tag_id = !empty($_REQUEST['file_tag_id']) ? $_REQUEST['file_tag_id'] : '0';//图文直播的某一消息中的文件编号，如果指定了该值，则只返回该文件编号的url地址，而不包含其他的内容
		/*$timestamp = !empty($_REQUEST['timestamp']) ? $_REQUEST['timestamp'] : '';
		$app_key = !empty($_REQUEST['app_key']) ? $_REQUEST['app_key'] : '';
		$sign = !empty($_REQUEST['sign']) ? $_REQUEST['sign'] : '';
		if(!$token){
			echo '未经授权访问！';exit;
		}*/
		$host =C('host');//http://www.nmaphp.com/live-panel/get-live-panel		
		$header = '';//Bearer '.$token;
		$curl = $host.'live-panel/get-live-panel';
		//$reponse = $this->curl_http($curl,array('live_id'=>$live_id,'timestamp'=>$timestamp,'app_key'=>$app_key,'unique'=>'xinhuiwen,fighting!','sign'=>$sign,'token'=>$token),array('Authorization:'.$header));
		$curl .= "?live_id=$live_id&msg_id=$msg_id&file_tag_id=$file_tag_id&".$this->make_sign_string()."&token=$token";
		$reponse = $this->curl_http($curl,array(),array('Authorization:'.$header));
		header('Content-Type:application/json; charset=utf-8');
		exit(json_encode($reponse));		
	}
	//Tah 20161215
	//删除面板中的图文消息
	function del_live_panel(){
		//$token = !empty($_REQUEST['token']) ? $_REQUEST['token'] : '';
		$live_id = !empty($_REQUEST['live_id']) ? $_REQUEST['live_id'] : '0';
		$msg_id = !empty($_REQUEST['msg_id']) ? $_REQUEST['msg_id'] : '0';
		/*$timestamp = !empty($_REQUEST['timestamp']) ? $_REQUEST['timestamp'] : '';
		 $app_key = !empty($_REQUEST['app_key']) ? $_REQUEST['app_key'] : '';
		$sign = !empty($_REQUEST['sign']) ? $_REQUEST['sign'] : '';
		if(!$token){
		echo '未经授权访问！';exit;
		}*/
		$host =C('host');//http://www.nmaphp.com/live-panel/get-live-panel
		$header = '';//Bearer '.$token;
		$curl = $host.'live-panel/del-live-panel';
		//$reponse = $this->curl_http($curl,array('live_id'=>$live_id,'timestamp'=>$timestamp,'app_key'=>$app_key,'unique'=>'xinhuiwen,fighting!','sign'=>$sign,'token'=>$token),array('Authorization:'.$header));
		$curl .= "?live_id=$live_id&".$this->make_sign_string()."&token=$token&msg_id=$msg_id";
		$reponse = $this->curl_http($curl,array(),array('Authorization:'.$header));
		header('Content-Type:application/json; charset=utf-8');
		exit(json_encode($reponse));		
	}
	//Tah 20161215
	//置顶图文消息
	function set_top_panel(){
		//$token = !empty($_REQUEST['token']) ? $_REQUEST['token'] : '';
		$live_id = !empty($_REQUEST['live_id']) ? $_REQUEST['live_id'] : '0';
		$msg_id = !empty($_REQUEST['msg_id']) ? $_REQUEST['msg_id'] : '0';
		/*$timestamp = !empty($_REQUEST['timestamp']) ? $_REQUEST['timestamp'] : '';
		 $app_key = !empty($_REQUEST['app_key']) ? $_REQUEST['app_key'] : '';
		$sign = !empty($_REQUEST['sign']) ? $_REQUEST['sign'] : '';
		if(!$token){
		echo '未经授权访问！';exit;
		}*/
		$host =C('host');//http://www.nmaphp.com/live-panel/get-live-panel
		$header = '';//Bearer '.$token;
		$curl = $host.'live-panel/set-top-panel';
		//$reponse = $this->curl_http($curl,array('live_id'=>$live_id,'timestamp'=>$timestamp,'app_key'=>$app_key,'unique'=>'xinhuiwen,fighting!','sign'=>$sign,'token'=>$token),array('Authorization:'.$header));
		$curl .= "?live_id=$live_id&".$this->make_sign_string()."&token=$token&msg_id=$msg_id";
		$reponse = $this->curl_http($curl,array(),array('Authorization:'.$header));
		header('Content-Type:application/json; charset=utf-8');
		exit(json_encode($reponse));
	}
	
	function set_result(){
		$live_id = I("get.live_id");
		$red_score = I("get.red_score");
		$blue_score = I("get.blue_score");
		$postData = array(
				'red_score'=>$red_score,
				'blue_score'=>$blue_score
		);
		$result = $this->live->where(array('live_id'=>$live_id))->save($postData);
		if($result){
			$this->success("设置成功！", U("Admin/Live/index"));
		}else{
			return $this->error("设置失败！");
		}
	}
	
	function set_status(){
		$live_id = I("get.live_id");
		$status = I("get.status");
		$add_from = I("get.add_from",0);
		$news_id = I("get.news_id",0);
		$id_type = I("get.id_type",'');
		$id_val  = I("get.id_val",'');

		if (gettype($status) == 'string'){
			$status = (int)$status;
			if($status == 0){
				return $this->error("设置失败！");
			}
		}else{
			if($status == 0){
				return $this->error("设置失败！");
			}
		}
		$postData = array(
				'status'=>$status
		);
		$result = $this->live->where(array('live_id'=>$live_id))->save($postData);
		if($result){
			if($status == '2'){
				//直播结束清空当前管理员的融云id
				$this->admin_user_rcloud_token->where(array('admin_id'=>$_SESSION["ADMIN_ID"]))->delete();
			}

			if($add_from == 1){
				$this->success("设置成功！", U('Admin/live/manage', array('news_id'=>$news_id, $id_type=>$id_val,'add_from'=>1)) );
			}else {
				$this->success("设置成功！", U("Admin/Live/index"));
			}
			
		}else{
			return $this->error("设置失败！");
		}
	}
	
	function get_channel_operators(){
		$channel_id = I("get.channel_id", 0);
		$list = $this->live_channel_operator->getOperatorListByChannelId($channel_id);
		$this->ajaxReturn(array('data'=>$list));
	}
	
	function news_relation(){
		$live_id  = I("get.live_id");
		$add_from = I("get.add_from") ? I("get.add_from") : 0;
		$list = $this->live_news_relation->get_news_relation_list($live_id);
		$data = array();
		if($list && !empty($list)){
			foreach($list as $key=>$value){
				$news = $this->news->where(array('news_id'=>$value['news_id']))->find();
				if($news && !empty($news)){
					$news['relation_id'] = $value['relation_id'];
					$news['type'] = $value['type'];
					$news['weight'] = $value['weight'];
					$data[] = $news;
				}
			}
		}
		
		$this->assign("add_from",$add_from);
		$this->assign('live_id', $live_id);
		$this->assign('data', $data);
		$this->display();
	}
	
	function delete_news_relation(){
		$live_id = trim(I('live_id'));
		$relation_id = I("get.relation_id");
		$result = $this->live_news_relation->where(array('relation_id' => $relation_id))->delete();
		if($result !== false){
 			$this->success("删除成功！", U("Admin/Live/news_relation", array('live_id'=>$live_id)));
		}else{
			return $this->error("删除失败！");
		}
	}
	
	function news_relation_add(){
 		$live_id = I("post.live_id");
		$news_url = I("post.news_url");
		
		parse_str($_POST['news_url'], $_relation);
		if(!$_relation['id'] || !$_relation['type']){
			return $this->error("相关新闻填写错误！");
		}
		
		if(empty($news_url)){
			return $this->error("URL不能为空！");
		}
		
		$news_weight = I("post.news_weight", 70);
		
		$news_status = $this->live->where(array('live_id'=>$live_id))->getField('status');
		
		if(1 == $news_status){
			$dataList = array();
			if('' != $news_url){
				$dataList = array('live_id'=>$live_id, 'news_id'=>$_relation['id'], 'type'=>$_relation['type'], 'weight'=>$news_weight);
				if(!empty($dataList)){
					$ret = $this->live_news_relation->add($dataList);
					if($ret){
						$this->success("添加成功！", U("Admin/Live/news_relation", array('live_id'=>$live_id)));
					}else{
						return $this->error("添加失败！");
					}
				}else{
					return $this->error("数据解析错误！");
				}
			}else{
				return $this->error("不能为空！");
			}
		}else{
			return $this->error("该直播状态错误！");
		}
	}
	
	function edit_news_weight(){
		$relation_id = I("post.relation_id", 0);
		$weight = I("post.weight", 0);
	
		$result = $this->live_news_relation->where(array('relation_id'=>$relation_id))->save(array('weight'=>$weight));
		if($result){
			$this->success("修改成功！", U("Admin/Live/news_relation", array('live_id'=>$live_id)));
		}else{
			return $this->error("修改失败！");
		}
	}
	
	
	function direct_manage(){
		$live_id = I("get.live_id");
		$add_from = I("get.add_from",0);
		$is_fast  = I("get.is_fast",0);
		$live_info = $this->live->where(array("live_id"=>$live_id))->find();
		//查询频道
		$channelList = $this->live_channel->getLiveChannelList($is_fast);
		//查询无输入流 频道
//		$channelList = $this->live_channel->getLiveChannelNoneList($is_fast,$live_info['start_time']);

		$channels = array();
		foreach($channelList as $key=>$value){
			$channels['n_'.$value['channel_id']] = $value['channel_name'];
			$channels['txy_'.$value['channel_id']] = $value['txy_channel_id'];
		}

		//查看 推流业务员
		$operatorList = $this->live_camera_angle->getLiveOperatorList();

		//查询视频资源
		$videoList = $this->live_resource_video->get_list($live_id);
		$videos = array();
		foreach($videoList as $key=>$value){
			$videos['n_'.$value['video_id']] = $value['video_name'];
			$videos['f_'.$value['video_id']] = $value['file_id'];
		}
		//查询机位
		$angleList = $this->live_camera_angle->get_camera_angle_list($live_id);
		
		if(!$angleList || empty($angleList)){
			$angleList = array();
		}else{
			foreach($angleList as $key=>&$value){
				//信号来源 1 频道 2 视频素材 3 外链素材
				if(1 == $value['signal_source']){
					if(!$value['source_name']) {
						$value['source_name'] = $channels['n_' . $value['source_id']];
						$value['txy_channel_id'] = $channels['txy_' . $value['source_id']];
					}
				}else {
					$value['source_name'] = $videos['n_'.$value['source_id']];
					$value['txy_channel_id'] = 0;
					$value['file_id'] = $videos['f_'.$value['source_id']];
				}
			}
		}
		$angleList[] = array();
		if(!$videoList || empty($videoList)){
			$videoList = array();
		}
		$videoList[] = array('video_id'=>0, 'video_name'=>'','file_name'=>'','category'=>1,'input_file_id'=>'');
		//获取融云token
		$admin = $this->admin_user_rcloud_token->find($_SESSION["ADMIN_ID"]);
		if(null == $admin || empty($admin)){
			$rcloud_token = $this->get_rcloud_token('ad_'.$_SESSION["ADMIN_ID"]);
			//创建token
			$data = array(
					'admin_id'=>$_SESSION["ADMIN_ID"],
					'rcloud_token'=>$rcloud_token
			);
			$this->admin_user_rcloud_token->add($data);
		}else{
			$rcloud_token = $admin['rcloud_token'];
		}
		
		
		$this->assign('admin_id', $_SESSION["ADMIN_ID"]);
		$this->assign('rcloud_token', $rcloud_token);
		$this->assign('ryAppKey', C('ryAppKey'));
		$this->assign('angleList', $angleList);
		$this->assign('channelList', json_encode($channelList, JSON_UNESCAPED_UNICODE));
		$this->assign('operatorList', json_encode($operatorList, JSON_UNESCAPED_UNICODE));
		$this->assign('videoList', $videoList);
		$this->assign('add_from', $add_from);
		$live = $this->live->find($live_id);
		$this->assign('live',$live);
		$this->assign($live);
		$this->display();
	}
	
	private function get_rcloud_token($user_id){
		$nonce = mt_rand();
		$timeStamp = time();
		$sign = sha1(C('ryAppSecret') . $nonce . $timeStamp);
		$header = array(
				'RC-App-Key:' . C('ryAppKey'),
				'RC-Nonce:' . $nonce,
				'RC-Timestamp:' . $timeStamp,
				'RC-Signature:' . $sign,
		);
		$data = 'userId=' . $user_id . '&name=新汇闻&portraitUri=';
		$result = $this->curl_http(C("ryApiUrl") . '/user/getToken.json', $data, $header);
		return $result['token'];
	}
	
	function edit_angle_name(){
		$camera_id = I("post.camera_id", 0);
		$name = I("post.name", "");
		
		$result = $this->live_camera_angle->where(array('camera_id'=>$camera_id))->save(array('name'=>$name));
		if($result){
			$this->success("修改成功！");
		}else{
			return $this->error("修改失败！");
		}
	}
	
	function view_live(){
		$signal_source = I("get.signal_source", 1);
		$this->assign("app_id", C('API_AppId'));
		if(1 == $signal_source){
			$channelId = I("get.channel_id", 0);
			$this->assign("channel_id", $channelId);
			$this->display('view_live');
		}else{
			$file_id = I("get.file_id", 0);
			$this->assign("file_id", $file_id);
			$this->display('view_video');
		}
	}
	
	function change_all_status(){
		$live_id = I("post.live_id");
		$status = I("post.status", 1);
		$result = $this->live_camera_angle->where(array('live_id'=>$live_id))->save(array('status'=>$status));
		$this->live->update_live_category($live_id);
		if($result){
			$this->success("修改成功！");
		}else{
			return $this->error("修改失败！");
		}
	}
	
	function edit_angle_status(){
		$camera_id = I("post.camera_id", 0);
		$status = I("post.status", 1);
		if(1 == $status){
			//关闭
			$status = 2;
		}else{
			//开启
			$status = 1;
		}
		
		$result = $this->live_camera_angle->where(array('camera_id'=>$camera_id))->save(array('status'=>$status));
		$this->live->update_live_category($live_id);
		if($result){
			
			$this->success("修改成功！"+$this->live_camera_angle->getLastInsID());
		}else{
			return $this->error("修改失败！");
		}
	}
	
	function add_camera_angle(){
		$live_id = I("post.live_id", 0);
		$name = I("post.name", "");
		$signal_source = I("post.signal_source", 1);
		$source_id = I("post.source_id", 0);
		$operator_id = I("post.operator_id", 0);
		if(empty($operator_id) || $signal_source != 1){
			$operator_id = 0;
		}
		if($operator_id != 0){
			//查看 之前存储 业务员信息
			$live_manager = M("vrlive.live_manager",null);
			$if_manager_res = $live_manager->where("live_id = ".$live_id)->select();

			//判断是否跟 直播指派 业务员 重复
			if($if_manager_res){
				//对比
				$if_manager_ids = array_column($if_manager_res, 'admin_id');
				$if_cou = in_array($operator_id, $if_manager_ids);
				if($if_cou){
					echo "两种业务员 不能重复";die;
				}
			}
		}
		$result = $this->live_camera_angle->add(array('live_id'=>$live_id,'signal_source'=>$signal_source,'name'=>$name,'source_id'=>$source_id,'operator_id'=>$operator_id));
		$this->live->update_live_category($live_id);
		if($result){
			$this->success("添加成功！");
		}else{
			echo "添加失败！";die;
			return $this->error("添加失败！");
		}
	}
	
	function update_camera_angle(){
		$live_id = I("post.live_id", 0);
		$camera_id = I("post.camera_id", 0);
		$name = I("post.name", "");
		$signal_source = I("post.signal_source", 1);
		$source_id = I("post.source_id", 0);
		$operator_id = I("post.operator_id", 0);
		if(empty($operator_id) || $signal_source != 1){
			$operator_id = 0;
		}
		if($operator_id != 0){
			//查看 之前存储 业务员信息
			$live_manager = M("vrlive.live_manager",null);
			$if_manager_res = $live_manager->where("live_id = ".$live_id)->select();

			//判断是否跟 直播指派 业务员 重复
			if($if_manager_res){
				//对比
				$if_manager_ids = array_column($if_manager_res, 'admin_id');
				$if_cou = in_array($operator_id, $if_manager_ids);
				if($if_cou){
					echo "两种业务员 不能重复";die;
				}
			}
		}
		$result = $this->live_camera_angle->where(array('camera_id'=>$camera_id))->save(array('signal_source'=>$signal_source,'name'=>$name,'source_id'=>$source_id,'operator_id'=>$operator_id));
		$this->live->update_live_category($live_id);
		if($result){
			$this->success("修改成功！");
		}else{
			echo "修改失败！";die;
			return $this->error("修改失败！");
		}
	}
	
	function angle_list(){
		$live_id = I("get.live_id");
		$is_fast = I("get.is_fast");
		//查询频道
		$channelList = $this->live_channel->getLiveChannelList($is_fast);
		$channels = array();
		foreach($channelList as $key=>$value){
			$channels['n_'.$value['channel_id']] = $value['channel_name'];
			$channels['txy_'.$value['channel_id']] = $value['txy_channel_id'];
		}
	    //查询视频资源
		$videoList = $this->live_resource_video->get_list($live_id);
		$videos = array();
		foreach($videoList as $key=>$value){
			$videos['n_'.$value['video_id']] = $value['video_name'];
			$videos['f_'.$value['video_id']] = $value['file_id'];
		}
		//查询机位
		$angleList = $this->live_camera_angle->get_camera_angle_list($live_id);
		if(!$angleList || empty($angleList)){
			$angleList = array();
		}else{
			foreach($angleList as $key=>&$value){
				//信号来源 1 频道 2 视频素材 3 外链素材
				if(1 == $value['signal_source']){
					$value['source_name'] = $channels['n_'.$value['source_id']];
					$value['txy_channel_id'] = $channels['txy_'.$value['source_id']];
				}else {
					$value['source_name'] = $videos['n_'.$value['source_id']];
					$value['txy_channel_id'] = 0;
					$value['file_id'] = $videos['f_'.$value['source_id']];
				}
			}
		}
		$angleList[] = array();
		
		$this->assign('angleList', $angleList);
		$live = $this->live->find($live_id);
		$this->assign('live',$live);
		$this->assign($live);
		$this->display();
	}
	
	function changeTimeType($seconds) {
		if ($seconds > 3600) {
			$hours = intval($seconds / 3600);
			$minutes = $seconds % 3600;
			$time = $hours . ":" . gmstrftime('%M:%S', $minutes);
		} else {
			$time = gmstrftime('%H:%M:%S', $seconds);
		}
		return $time;
	}
	
	/**
	 *  后台修改观看人数  数据库  play_count 字段 
	 */
	public function editLiveCount(){
		$type = I('post.type');
		$live_id = I('post.live_id');
		$current_live_count = I('post.val');
// 		$old_live_count = I('post.old_val');

		if($type != 'live' || !$live_id){
			echo $this->ajaxReturn(array('code'=>404, 'msg'=>'修改的直播不存在'), 'JSON');
			exit();
		}
		
		$ret = $this->live->updateLiveCount($live_id, $current_live_count);
		
		if($ret){
			echo $this->ajaxReturn(array('code'=>200, 'msg'=>''), 'JSON');
		}else{
			echo $this->ajaxReturn(array('code'=>400, 'msg'=>'保存失败，请稍后再试！'), 'JSON');
		}
		
		exit();
	}
	
	/*
	 *  后台刷新直播的排序时间  
	 **/
	public function refreshLiveTime(){
		$live_id = I("news_id");
		$data['refresh_time'] = date('Y-m-d H:i:s', time());
		echo $this->live->where(array('live_id'=>$live_id))->save($data);
		exit();
	}
	
	/**
	 *  修改排序
	 */
	
	public function changeWeight(){
		$live_id = I('post.live_id');
		$weight  = I('post.weight');
		
		if(!$live_id || $weight > 255 || $weight < 0){return false;}
		
		$ret = M('vrlive.live')->where(array('live_id'=>$live_id))->save(array('weight'=>$weight));
	
		echo $ret;
		exit();
	}
	
	public function getNextSortNumber(){
		$sort_number = 0;
		$sql = 'select ifnull(max(sort_number),0)+1 as next_sort_number from vrlive.live_panel_manage';
		$list=$this->live->query($sql);
		if($list && !empty($list)){
			foreach($list as $key=>$value){
				$sort_number = $value['next_sort_number'];
				break;
			}
		}
		if (empty($sort_number)){
			$sort_number=1;
		}
		return $sort_number;
	}
}